package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.product.entity.GlobalSpecTemplate;
import com.dms.modules.product.mapper.GlobalSpecTemplateMapper;
import com.dms.modules.product.service.GlobalSpecTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class GlobalSpecTemplateServiceImpl extends ServiceImpl<GlobalSpecTemplateMapper, GlobalSpecTemplate> implements GlobalSpecTemplateService {

    @Override
    public List<GlobalSpecTemplate> getEnabledSpecs() {
        return list(new LambdaQueryWrapper<GlobalSpecTemplate>()
                .eq(GlobalSpecTemplate::getStatus, 1)
                .orderByAsc(GlobalSpecTemplate::getSort));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Boolean enabled) {
        GlobalSpecTemplate template = getById(id);
        if (template == null) {
            throw new BusinessException("规格模板不存在");
        }
        template.setStatus(enabled ? 1 : 0);
        return updateById(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createGlobalSpec(GlobalSpecTemplate template) {
        // 检查名称是否重复
        if (checkNameExists(template.getName(), null)) {
            throw new BusinessException("规格名称已存在");
        }
        template.setStatus(1); // 默认启用
        return save(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGlobalSpec(GlobalSpecTemplate template) {
        // 检查名称是否重复
        if (checkNameExists(template.getName(), template.getId())) {
            throw new BusinessException("规格名称已存在");
        }
        return updateById(template);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteGlobalSpec(Long id) {
        GlobalSpecTemplate template = getById(id);
        if (template == null) {
            throw new BusinessException("规格模板不存在");
        }
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteGlobalSpecs(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return removeBatchByIds(ids);
    }

    private boolean checkNameExists(String name, Long excludeId) {
        LambdaQueryWrapper<GlobalSpecTemplate> wrapper = new LambdaQueryWrapper<GlobalSpecTemplate>()
                .eq(GlobalSpecTemplate::getName, name);
        if (excludeId != null) {
            wrapper.ne(GlobalSpecTemplate::getId, excludeId);
        }
        return count(wrapper) > 0;
    }
} 